#include <main_window/mainwindow.h>
#include "./ui_mainwindow.h"
#include <utils/config.h>
#include <data_display/accountDataDialog.h>
#include <data_display/totpwindow.h>
#include <users/user.h>
#include <totp/totp.h>
#include <totp/totpManager.h>

namespace main_window {
MainWindow::MainWindow(utils::config& config,QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow), _config(config), _clipboard_watcher(this) {
    ui->setupUi(this);
	ui->table->setColumnCount(2);
	ui->table->setHorizontalHeaderLabels({"Сервис", "Логин"});
	ui->table->setSelectionMode(QAbstractItemView::SingleSelection);
	ui->table->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui->table->setContextMenuPolicy(Qt::CustomContextMenu);
	setWindowTitle("Lorepana");
	setWindowIcon(QIcon(":/resources/small_icon.png"));
	connect(ui->table, &QTableWidget::customContextMenuRequested, this, &MainWindow::showContextMenu);
	createContextMenu();
	createTrayIcon();

	connect(ui->table, &QTableWidget::cellDoubleClicked, this, &MainWindow::openAccWindow);
	connect(&_clipboard_watcher, &utils::ClipboardWatcher::clipboardCleared, this, &MainWindow::showClearedPopup);
	trayIcon->show();
}

MainWindow::~MainWindow() {
	if(_manag && _sdm)
		_manag->WriteData(*_sdm);
	if(_totpManager)
		_totpManager->saveTOTPs();

	trayIcon->hide();
	delete ui;
}

void MainWindow::createContextMenu() {
	tableContextMenu = new QMenu(this);
	copyPasswordAction = new QAction("Скопировать пароль", this);
	deleteRowAction = new QAction("Удалить", this);

	connect(copyPasswordAction, &QAction::triggered, this, &MainWindow::copyPassword);
	connect(deleteRowAction, &QAction::triggered, this, &MainWindow::deleteRow);

	tableContextMenu->addAction(copyPasswordAction);
	tableContextMenu->addAction(deleteRowAction);
}

void MainWindow::createTrayIcon() {
	trayIconMenu = new QMenu(this);

	openTotpAction = new QAction(tr("Открыть TOTP"), this);
	connect(openTotpAction, &QAction::triggered, this, &MainWindow::openTotp);

	minimizeAction = new QAction(tr("Свернуть"), this);
	connect(minimizeAction, &QAction::triggered, this, &QWidget::hide);

	restoreAction = new QAction(tr("Развернуть"), this);
	connect(restoreAction, &QAction::triggered, this, &QWidget::showNormal);

	quitAction = new QAction(tr("Закрыть приложение"), this);
	connect(quitAction, &QAction::triggered, qApp, &QCoreApplication::quit);


	trayIconMenu->addAction(openTotpAction);
	trayIconMenu->addSeparator();
	trayIconMenu->addAction(minimizeAction);
	trayIconMenu->addAction(restoreAction);
	trayIconMenu->addSeparator();
	trayIconMenu->addAction(quitAction);

	trayIcon = new QSystemTrayIcon(this);
	trayIcon->setContextMenu(trayIconMenu);
	trayIcon->setIcon(QIcon(":/resources/small_icon.png")); // Установите здесь путь к вашей иконке

	connect(trayIcon, &QSystemTrayIcon::activated, this, &MainWindow::trayIconActivated);
}

void MainWindow::trayIconActivated(QSystemTrayIcon::ActivationReason reason) {
	if (reason == QSystemTrayIcon::Trigger) {
		if (isVisible()) {
			hide();
		} else {
			showNormal();
		}
	}
}

void MainWindow::closeEvent(QCloseEvent *event) {
	if (trayIcon->isVisible()) {
		hide();
		event->ignore();
	}
}
void MainWindow::showContextMenu(const QPoint &pos) {
	QModelIndex index = ui->table->indexAt(pos);
	if (index.isValid()) {
		tableContextMenu->exec(ui->table->viewport()->mapToGlobal(pos));
	}
}

void MainWindow::copyPassword() {
	QModelIndexList selectedRows = ui->table->selectionModel()->selectedRows();

	if (!selectedRows.isEmpty()) {
		QModelIndex index = selectedRows.first();
		auto serviceName = ui->table->item(index.row(), 0)->text().toStdString();
		auto loginName = ui->table->item(index.row(), 1)->text().toStdString();

		auto &data = *_sdm->getDataViaLoginAndServiceName(loginName, serviceName);
		_clipboard_watcher.setClipboardData(data.getDecryptedData(utils::DataType::PASSWORD));
		_popup = new utils::PopUp(QWidget::geometry(), this);
		_popup->setPopupText("Пароль скопирован");
		_popup->show();
	}
}

void MainWindow::deleteRow() {
	QModelIndexList selectedRows = ui->table->selectionModel()->selectedRows();

	if (!selectedRows.isEmpty()) {
		QModelIndex index = selectedRows.first();
		auto serviceName = ui->table->item(index.row(), 0)->text().toStdString();
		auto loginName = ui->table->item(index.row(), 1)->text().toStdString();

		auto it = _sdm->getDataViaLoginAndServiceName(loginName, serviceName);
		_sdm->deleteItem(it);
		ui->table->removeRow(index.row());
	}
}



void MainWindow::setUser(const users::user& user_) {
	_user  = user_;
    _manag = std::make_unique<crypto::cryptomanager>(_config.pathToUsersSecrets/user_._dataPath, user_._cipher_algorithm_, user_.generatePass());
    _sdm =  std::make_unique<crypto::SecureDataMap>(_manag->getData());
	_totpManager = std::make_unique<totp::TOTPManager>(_config.pathToUsersSecrets/user_._totpPath, user_._cipher_algorithm_, user_.generatePass());
	fillTable();
}

void MainWindow::on_saveButton_clicked() {
	_dataDialog = new data_display::accountDataDialog(_clipboard_watcher, nullptr, _sdm->getCipherManager());
	connect(_dataDialog, &data_display::accountDataDialog::sendData, this, &MainWindow::addDataToSecureDataMap);
	_dataDialog->setModal(true);
	_dataDialog->show();
	_dataDialog->exec();
}

void MainWindow::addDataToSecureDataMap(const crypto::SecureDataMapItem &item) {
	_sdm->addItemBySecureDataItem(item);
	fillTable();
}

void MainWindow::openAccWindow() {
	QModelIndexList selectedRows = ui->table->selectionModel()->selectedRows();

	// Проверяем, есть ли выбранные строки
	if (!selectedRows.isEmpty()) {
		// Получаем индекс первой выбранной строки
		QModelIndex index = selectedRows.first();

		// Получаем данные из первого и второго столбца выбранной строки
		auto serviceName = ui->table->item(index.row(), 0)->text().toStdString(); // Предположим, что имя службы находится в первом столбце
		auto loginName = ui->table->item(index.row(), 1)->text().toStdString(); // Предположим, что имя входа находится во втором столбце

		// Используем данные для получения нужных данных из _sdm
		auto &data = *_sdm->getDataViaLoginAndServiceName(loginName, serviceName);
		_dataDialog = new data_display::accountDataDialog(_clipboard_watcher, nullptr, &data);
		_dataDialog->show();
		_dataDialog->exec();
		fillTable();
		// Обрабатываем полученные данные...
	}
}

void MainWindow::fillTable() {
	ui->table->setRowCount(0);
	for(const auto& item : *_sdm) {
		auto tableItem1 = new QTableWidgetItem();
		tableItem1->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
		tableItem1->setData(0, item.getDecryptedData(utils::DataType::SERVICE_NAME));
		auto *tableItem2 = new QTableWidgetItem();
		tableItem2->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
		tableItem2->setData(0, item.getDecryptedData(utils::DataType::LOGIN));
		ui->table->insertRow(ui->table->rowCount());
		ui->table->setItem(ui->table->rowCount()-1,
							 0,
							 tableItem1);
		ui->table->setItem(ui->table->rowCount()-1,
					   1,
					   tableItem2);
	}
}


void MainWindow::showClearedPopup() {
	_popup = new utils::PopUp(QWidget::geometry(), this);
	_popup->setPopupText("Данные из буфера обмена очищены");
	_popup->show();
}

void MainWindow::addTOTP(const totp::TOTP& totp) {
	_totpManager->addTOTP(totp);
}

void MainWindow::deleteTOTP(const totp::TOTP& totp) {
	_totpManager->deleteTOTP(totp);
}

void MainWindow::openTotp() {
	_totpDialog = new data_display::TOTPWindow(_totpManager->getTOTPs(), _clipboard_watcher, this);
	connect(_totpDialog, &data_display::TOTPWindow::addedTotp, this, &MainWindow::addTOTP);
	connect(_totpDialog, &data_display::TOTPWindow::deleteTotp, this, &MainWindow::deleteTOTP);
	_totpDialog->setModal(true);
	_totpDialog->setAttribute(Qt::WA_DeleteOnClose);
	_totpDialog->exec();
}

void MainWindow::on_totpButton_clicked() {
	openTotp();
}
}